const stack = []
let pointer = null
export default function (tokens, data) {
    const allTokens = []
    allTokens.push(...handleTokens(tokens))
    const result = nestedTokens(allTokens)
    console.log('🚀 ~ file: Combine.js:7 ~ result:', result)
    return assignTokensData(result, data)
}
// 处理tokens
function handleTokens(tokens) {
    return tokens.map(token => {
        if (token[1].indexOf('#') === 0) {
            token = ['#', token[1].slice(1)]
        } else if (token[1].indexOf('/') === 0) {
            token = ['/', token[1].slice(1)]
        }
        return token
    })
}
// 折叠tokens
function nestedTokens(tokens) {
    const res = []
    pointer = res
    tokens.forEach(token => {
        switch (token[0]) {
            case '#':
                stack.push(token)
                token[2] = []
                pointer = token[2]
                break
            case '/':
                const t = stack.pop()
                pointer = stack.length ? stack[stack.length - 1] : res
                pointer.push(t)
                break
            default:
                pointer.push(token)
                break
        }
    });
    return res
}
// 为tokens赋值
function assignTokensData(tokens, data) {
    let res = ``
    tokens.forEach(token => {
        switch (token[0]) {
            case 'name':
                if (token[1] === '.') res += data
                else res += lookup(data, token[1])
                break
            case '#':
                res += data[token[1]].map(object => assignTokensData(token[2], object)).join('')
                break
            default:
                res += token[1]
                break
        }
    })
    return res
}

function lookup(data, path) {
    return path.split('.').reduce((tar, cur) => tar[cur], data)
}